package com.comecrd.controller;

import com.comecrd.model.Like;
import com.comecrd.service.LikeService;
import com.comecrd.service.UserService;
import com.comecrd.service.CheckInService;
import com.comecrd.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/like")
public class LikeController {
    
    @Autowired
    private LikeService likeService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CheckInService checkInService;
    
    @Autowired
    private JWTUtil jwtUtil;
    
    // 点赞/取消点赞
    @PostMapping("/toggle")
    public ResponseEntity<Map<String, Object>> toggleLike(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Long> request) {
        
        Long checkInId = request.get("checkInId");
        
        // 从token中获取openId
        String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
        
        // 查找用户
        com.comecrd.model.User user = userService.findByOpenId(openId);
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 使用CheckInService的toggleLike方法处理点赞/取消点赞
        Map<String, Object> result = checkInService.toggleLike(checkInId, user.getId());
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("liked", result.get("isLiked"));
        response.put("likeCount", result.get("likeCount"));
        
        return ResponseEntity.ok(response);
    }
    
    // 检查是否已点赞
    @GetMapping("/status/{checkInId}")
    public ResponseEntity<Map<String, Object>> getLikeStatus(
            @PathVariable Long checkInId,
            @RequestHeader("Authorization") String token) {
        
        // 从token中获取openId
        String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
        
        // 查找用户
        com.comecrd.model.User user = userService.findByOpenId(openId);
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 检查是否已点赞
        boolean isLiked = likeService.isLiked(user.getId(), checkInId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("liked", isLiked);
        
        return ResponseEntity.ok(response);
    }
}